package com.guit.hrms.service.impl;

import com.guit.hrms.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class TokenServiceImpl implements TokenService {

    private static final String TOKEN_KEY_PREFIX = "user:token:";

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Value("${jwt.expiration:28800}")
    private long tokenExpiration;

    /**
     * 保存用户token
     * @param employeeId 用户ID
     * @param token 用户token
     * @return 如果有旧token，返回旧token；否则返回null
     */
    public String saveToken(String employeeId, String token) {
        String key = TOKEN_KEY_PREFIX + employeeId;
        String oldToken = redisTemplate.opsForValue().get(key);
        redisTemplate.opsForValue().set(key, token, tokenExpiration, TimeUnit.SECONDS);
        return oldToken;
    }

    /**
     * 验证token是否是当前有效token
     * @param employeeId 用户ID
     * @param token 待验证的token
     * @return 是否有效
     */
    public boolean validateToken(String employeeId, String token) {
        String key = TOKEN_KEY_PREFIX + employeeId;
        String currentToken = redisTemplate.opsForValue().get(key);
        return token != null && token.equals(currentToken);
    }

    /**
     * 删除用户token(登出时使用)
     * @param employeeId 用户ID
     */
    public void removeToken(String employeeId) {
        String key = TOKEN_KEY_PREFIX + employeeId;
        redisTemplate.delete(key);
    }
}